package online.dgyj.ultrasonic;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.nle.mylibrary.claimer.connector.ConnectorListener;
import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.device.GenericConnector;
import com.nle.mylibrary.device.listener.ConnectResultListener;

import java.util.concurrent.TimeUnit;

@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Handler handler;
    private GenericConnector genericConnector;
    private String ip;
    private int port, address;
    private final Thread getSensorThread = getSensor();


    private TextView sensor1Text;
    private TextView sensor1Value;
    private EditText IPEdit, PortEdit, AddressEdit;
    private Switch RTUSwitch;
    private Button LinkBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        bind();
    }

    /**
     * 初始化视图
     * 此方法主要适配通用UI,正常不推荐
     */
    private void InitView() {
        sensor1Text.setText("处理值");
    }

    /**
     * 实例化控件
     */
    private void bind() {

        handler = new Handler(Looper.getMainLooper());

        sensor1Text = findViewById(R.id.sensor1Text);

        sensor1Value = findViewById(R.id.sensor1Value);

        IPEdit = findViewById(R.id.IPEdit);
        PortEdit = findViewById(R.id.PortEdit);
        AddressEdit = findViewById(R.id.AddressEdit);

        RTUSwitch = findViewById(R.id.RTUSwitch);

        LinkBtn = findViewById(R.id.LinkBtn);

        InitView();

        LinkBtn.setOnClickListener(this);   // 事件处理

        RTUSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // 事件处理
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    IPEdit.setHint("SerialName");
                    PortEdit.setHint("Baud");
                    IPEdit.setText("");
                    PortEdit.setText("");
                } else {
                    IPEdit.setHint("IP");
                    PortEdit.setHint("Port");
                    IPEdit.setText("");
                    PortEdit.setText("");
                }
            }
        });
    }

    /**
     * 获取处理值
     * 经过测试只有处理值可用,且1为处理值
     *
     * @return 线程
     */
    private Thread getSensor() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        genericConnector.sendUltrasonicValue(address, 1, new ConnectorListener() {
                            @Override
                            public void onSuccess(boolean b) {
                                int data = genericConnector.getUltrasonicValue();
                                Log.i("ProcessValue", String.valueOf(data));
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        sensor1Value.setText(String.valueOf(data));
                                    }
                                });
                            }

                            @Override
                            public void onFail(Exception e) {

                            }
                        });
                    } catch (InterruptedException e) {
                        break;
                    } catch (Exception e) {
                        Log.e("getProcessValue", e.toString());
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.LinkBtn) {
            if (genericConnector == null) {
                ip = IPEdit.getText().toString();
                port = Integer.parseInt(PortEdit.getText().toString());
                address = Integer.parseInt(AddressEdit.getText().toString());
                if (RTUSwitch.isChecked()) {
                    Log.i("Start", "Start");
                    genericConnector = new GenericConnector(DataBusFactory.newSerialDataBus(Integer.parseInt(ip), port), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("Rtu Status", "Link OK");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        IPEdit.setEnabled(false);
                                        PortEdit.setEnabled(false);
                                        AddressEdit.setEnabled(false);
                                        RTUSwitch.setEnabled(false);
                                        LinkBtn.setText("DISC");
                                        Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                getSensorThread.start();
                            } else {
                                Log.e("Rtu Status", "Link Error");
                                genericConnector = null;// 销毁
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                } else {
                    genericConnector = new GenericConnector(DataBusFactory.newSocketDataBus(ip, port), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("tcp Status", "Link OK");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        IPEdit.setEnabled(false);
                                        PortEdit.setEnabled(false);
                                        AddressEdit.setEnabled(false);
                                        RTUSwitch.setEnabled(false);
                                        LinkBtn.setText("DISC");
                                        Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                getSensorThread.start();
                            } else {
                                Log.e("tcp Status", "Link Error");
                                genericConnector = null;// 销毁
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }
            } else {
                getSensorThread.interrupt();

                IPEdit.setEnabled(true);
                PortEdit.setEnabled(true);
                AddressEdit.setEnabled(true);
                RTUSwitch.setEnabled(true);

                LinkBtn.setText("Link");

                Toast.makeText(getApplication(), "断开连接", Toast.LENGTH_SHORT).show();

                // 销毁
                genericConnector.stopConnect();
                genericConnector = null;
            }
        }
    }
}